//
//  MyMainViewController.m
//  OAProject
//
//  Created by yhj on 2017/2/20.
//  Copyright © 2017年 cdnunion. All rights reserved.
//  我的主界面

#import "MyMainViewController.h"
#import "CheckOnMainViewController.h"
#import "HelpFeekBackMainViewController.h"
#import "PhotoMainViewController.h"
#import "SetMainViewController.h"
#import "MyMainInfoTableViewCell.h"
#import "MyDetailInfoViewController.h"

#import <ImageIO/ImageIO.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "MyHeadView.h"
#import "RequestTool.h"
#import "LoginViewController.h"

static NSString *myMainInfoTableViewCellIdentifier=@"MyMainInfoTableViewCellIdentifier";
static NSString *tableViewCellIdentifier=@"UITableViewCellIdentifier";
@interface MyMainViewController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property(nonatomic,strong)UITableView *myMainTableView;

//@property(nonatomic,strong)UserModel *userModel;

@property(nonatomic,strong)MyHeadView *myHeadView;

@property(nonatomic,assign)BOOL isLogout;

@end


@implementation MyMainViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

     self.title=@"我的";



    [self.view addSubview:self.myMainTableView];

//    __weak typeof(self) weakSelf=self;
//    self.myMainTableView.mj_header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [weakSelf getData];
//
//        [weakSelf get];
//
//    }];
//    [self.myMainTableView.mj_header beginRefreshing];

}

-(MyHeadView *)myHeadView
{
    if (!_myHeadView) {
        _myHeadView=[[MyHeadView alloc]initWithFrame:CGRectMake(0,0,APPW,100)];
        _myHeadView.backgroundColor=WhiteColor;
//        setViewHeight_Add(_myHeadView,kmargin*10);
    }
    return _myHeadView;
}

//-(void)get
//{
//    [API getCountDataWithSuccess:^(TaskModel *taskModel, UserModel *userModel) {
//
//        NSLog(@"sdlkjsdjs---");
//        
//    } Failure:^(NSInteger stateCode) {
//
//    }];
//
//}
//
//
//-(void)getData
//{
//    [API getUserInfoWithSuccess:^(UserModel *userModel) {
//
//        NSLog(@"sdhjsdhhd--%@",userModel);
//        
//        self.userModel=userModel;
//
//        [self.myMainTableView.mj_header endRefreshing];
//        [self.myMainTableView reloadData];
//
//    } failure:^(NSInteger stateCode) {
//
//         [self.myMainTableView.mj_header endRefreshing];
//
//    }];
//
////    [API getUserInfoWithSuccess:^(us *contactModel) {
////
////        NSLog(@"888--%@",contactModel);
////        self.contactModel=contactModel;
////
////        [self.myMainTableView.mj_header endRefreshing];
////        [self.myMainTableView reloadData];
////
////    } failure:^(NSInteger stateCode) {
////
////         [self.myMainTableView.mj_header endRefreshing];
////
////    }];
//
//
////    [API getContactListWithSuccess:^(NSArray *contacts) {
////
//////        self.contactMainArr=[NSMutableArray arrayWithArray:contacts];
////        [self.myMainTableView.mj_header endRefreshing];
////        [self.myMainTableView reloadData];
////
////    } failure:^(NSInteger stateCode) {
////
////        [self.myMainTableView.mj_header endRefreshing];
////        
////    }];
//
//}


// myMainTableView
-(UITableView *)myMainTableView
{
    if (!_myMainTableView) {
        _myMainTableView=[[UITableView alloc]initWithFrame:CGRectMake(0,0,APPW,APPH) style:UITableViewStylePlain];
        _myMainTableView.dataSource=self;
        _myMainTableView.delegate=self;
        _myMainTableView.backgroundColor=MAIN_BACK_COLOR;
        _myMainTableView.showsVerticalScrollIndicator=NO;
        _myMainTableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
        self.myMainTableView.tableFooterView=[UIView new];
//        _myMainTableView.tableHeaderView=self.myHeadView;
        [self.myMainTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:tableViewCellIdentifier];
        [_myMainTableView registerClass:[MyMainInfoTableViewCell class] forCellReuseIdentifier:myMainInfoTableViewCellIdentifier];
    }
    return _myMainTableView;
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0)
    {
        return 1;
    }
    else
    {
        return 5;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0)
    {
        MyMainInfoTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:myMainInfoTableViewCellIdentifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
//        cell.userModel=self.userModel;
        return cell;
    }
    else
    {
        NSArray *arrImage=@[@"check",@"photo",@"help",@"set",@"logout"];
        NSArray *arrTitle=@[@"考勤",@"上传图片",@"帮助与反馈",@"设置",@"注销"];


        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:tableViewCellIdentifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text=arrTitle[indexPath.row];
        cell.imageView.image=[UIImage imageNamed:arrImage[indexPath.row]];
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0)
    {
        return kmargin*10;
    }
    else
    {
        return kmargin*5;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    // 获取_myMainTableView 当前选中的cell
    UITableViewCell *cell=[_myMainTableView cellForRowAtIndexPath:indexPath];
    if (indexPath.section==0)
    {

         [self.view makeToast:@"暂无" duration:.5 position:CSToastPositionCenter];

//        // 我的详情信息
//        MyDetailInfoViewController *myDetailInfoViewController=[[MyDetailInfoViewController alloc]initWithUserModel:self.userModel];
//        myDetailInfoViewController.hidesBottomBarWhenPushed=YES;
//        [self.navigationController pushViewController:myDetailInfoViewController animated:NO];
    }
    else
    {
        if (indexPath.row==0)
        {
            // 考勤
//            CheckOnMainViewController *check=[CheckOnMainViewController new];
//            check.title=cell.textLabel.text;
//            check.hidesBottomBarWhenPushed=YES;
//            [self.navigationController pushViewController:check animated:NO];


            [self.view makeToast:@"暂无" duration:.5 position:CSToastPositionCenter];
            
        }
        else if (indexPath.row==1)
        {
            // 上传图片
//            [self uploadPhoto];

            [self.view makeToast:@"暂无" duration:kGapTime position:CSToastPositionCenter];

        }
        else if (indexPath.row==2)
        {
            // 帮助与反馈
            HelpFeekBackMainViewController *helpAndFeedBack=[HelpFeekBackMainViewController new];
            helpAndFeedBack.title=cell.textLabel.text;
            helpAndFeedBack.hidesBottomBarWhenPushed=YES;
            [self.navigationController pushViewController:helpAndFeedBack animated:NO];
        }
        else if (indexPath.row==3)
        {
             [self.view makeToast:@"暂无" duration:.5 position:CSToastPositionCenter];
            
//            // 设置
//            SetMainViewController *set=[SetMainViewController new];
//            set.title=cell.textLabel.text;
//            set.hidesBottomBarWhenPushed=YES;
//            [self.navigationController pushViewController:set animated:NO];
        }
        else
        {
            UIAlertView *alert=[UIAlertView alertViewWithTitle:@"提示" message:@"你确定要退出登录吗？" cancelButtonTitle:@"取消" didDismissBlock:^(UIAlertView *alertView,NSInteger buttonIndex) {

                if (buttonIndex==0)
                {
                    // 退出登录
                    [self logout];
                }
            } otherButtonTitles:@"确定", nil];
            [alert show];
        }
    }
}

-(void)logout
{
    NSDictionary *params=@{
                           @"token":[Util getUserDefaultObjectForKey:@"Token"]
                           };
    [RequestTool PostCallBack:LogoutURL parameter:params success:^(id responseObj) {

        [self.view makeToast:@"退出登录" duration:1 position:CSToastPositionCenter];

        [self clearUserData];

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(1.0*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            if ([responseObj[@"rt"] isEqual:@(1)])
            {
                AppDelegate *delegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
                delegate.window.rootViewController=[LoginViewController new];
            }
        });
    } failure:^(NSError *error) {

        // 登录失败处理
        NSData *errorData=[[error userInfo] objectForKey:@"com.alamofire.serialization.response.error.data"];
        id jsonObject=[NSJSONSerialization JSONObjectWithData:errorData options:NSJSONReadingMutableLeaves error:nil];
        if ([jsonObject[@"rt"] isEqual:@(0)])
        {
            [self.view makeToast:jsonObject[@"error"] duration:1 position:CSToastPositionCenter];
        }
    }];
}


-(void)clearUserData
{
    [UserDefaults userDefaultsRemove:@"passwd"];
    [UserDefaults userDefaultsRemove:ISLogin];
    [UserDefaults userDefaultsRemove:@"Token"];
    [UserDefaults userDefaultsRemove:@"TToken"];
    [UserDefaults userDefaultsRemove:@"access_key"];
    [UserDefaults userDefaultsRemove:@"access_secret"];
    [UserDefaults userDefaultsRemove:@"bucket"];
    [UserDefaults userDefaultsRemove:@"host"];
}

// 间隙置边
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{

    if ([tableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }

    if ([tableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }

    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

// 上传照片
-(void)uploadPhoto
{
    UIAlertController *alertController=[UIAlertController new];
    // 取消
    UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

    }];
    [alertController addAction:cancelAction];

    // 相册
    UIAlertAction *albumAction=[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showImagePickerFromAlbum];
    }];
    [alertController addAction:albumAction];

    // 拍照
    UIAlertAction *takePhotoAction=[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showImagePickerTotakePhoto];
    }];
    [alertController addAction:takePhotoAction];
    [self presentViewController:alertController animated:NO completion:nil];

}

-(void)showImagePickerTotakePhoto
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] init];
        imagePickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePickerVC.allowsEditing = NO;
        imagePickerVC.delegate = self;
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self presentViewController:imagePickerVC animated:YES completion:NULL];
        //        });
    }
}


-(void)showImagePickerFromAlbum
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] init];
        imagePickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePickerVC.allowsEditing = NO;
        imagePickerVC.delegate = self;
        [self presentViewController:imagePickerVC animated:YES completion:NULL];
    }
}

#pragma mark - <UIImagePickerControllerDelegate>
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)Picker
{
    [Picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)Picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage * image             =(UIImage *)[info valueForKey:UIImagePickerControllerOriginalImage];

    NSDictionary *metadata      = [info objectForKey:UIImagePickerControllerMediaMetadata];

    NSLog(@"90999889---%@",image);
    PhotoMainViewController *photoMainViewController=[[PhotoMainViewController alloc]initWithImage:image];
    photoMainViewController.imageData=[self dataFromImage:image metadata:metadata mimetype:@"image/jpeg"];
    [Picker pushViewController:photoMainViewController animated:NO];
    [Picker setNavigationBarHidden:NO animated:NO];
}


- (NSData *)dataFromImage:(UIImage *)image metadata:(NSDictionary *)metadata mimetype:(NSString *)mimetype
{
    NSMutableData *imageData = [NSMutableData data];
    CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, (__bridge CFStringRef)mimetype, NULL);
    CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, uti, 1, NULL);

    if (imageDestination == NULL)
    {
        NSLog(@"Failed to create image destination");
        imageData = nil;
    }
    else
    {
        CGImageDestinationAddImage(imageDestination, image.CGImage, (__bridge CFDictionaryRef)metadata);

        if (CGImageDestinationFinalize(imageDestination) == NO)
        {
            NSLog(@"Failed to finalise");
            imageData = nil;
        }
        CFRelease(imageDestination);
    }

    CFRelease(uti);
    
    return imageData;
}

@end
